import mqtt from 'mqtt';

const MQTT_ADDRESS = 'ws://43.139.41.57:9001'; // MQTT Broker 地址

class MQTTService {
    constructor() {
        this.client = null;
    }

    connect() {
        return new Promise((resolve, reject) => {
            this.client = mqtt.connect(MQTT_ADDRESS);

            this.client.on('connect', () => {
                console.log('MQTT Connected');
                this.client.subscribe('state/#'); // 设备状态
                // 订阅其他所需主题...

                resolve(); // 连接成功，resolve Promise
            });

            this.client.on('error', (err) => {
                console.error('MQTT Connection Error:', err);
                reject(err); // 连接失败，reject Promise
            });

            this.client.on('message', (topic, message) => {
                // 处理接收到的消息
                console.log(`Received message from topic: ${topic}`);
            });
        });
    }

    sendMessage(topic, message) {
        if (this.client) {
            this.client.publish(topic, message);
        }
    }
}

export default new MQTTService();
